import { sanitizeActiveWhen } from '../../core/activeWhen';
import * as  qiankun from 'qiankun'
import React from 'react';
// import { pathToActiveWhen as singleSpaPathToActiveWhen } from 'single-spa';

// export function sanitizeActiveWhen(activeWhen) {
//   let activeWhenArray = Array.isArray(activeWhen) ? activeWhen : [activeWhen];
//   activeWhenArray = activeWhenArray.map((activeWhenOrPath) =>
//     typeof activeWhenOrPath === "function"
//       ? activeWhenOrPath
//       : singleSpaPathToActiveWhen(activeWhenOrPath)
//   );

//   return (location: any) => {
//     return activeWhenArray.some((activeWhen) => activeWhen(location));
//   }
// }
export const onRoutesChange = (routes) => {
  const qiankunApp = routes.filter(item => item.activeRule);
  qiankun.prefetchApps(qiankunApp);
  // if (qiankunApp.length > 0) {
  //   qiankun.registerMicroApps(qiankunApp);
  // }
}
const started ={

}
export const MicroApp = ({ name,entry, container,activeRule, onLoad }) => {
  debugger
  React.useEffect(() => {
    
    // if(started[name]){
      
    //   return
    // }
    qiankun.registerMicroApps([
      {
        name,
        container,
        activeRule,
        
        loader(loading) {
            if(!loading){
              onLoad()
            }
        },
        entry
      }
    ])
    qiankun.start({
      
      singular: false
    })
    started[name] = true
   
  }, [])
  return <div id={container.replace('#', '')} />
}


export const activeRule = (item: any) => {
  if (item.activeRule) {
    
    return sanitizeActiveWhen(item.activeRule)(location)
 
  }
  return false
}
export default {
  activeRule,
  MicroApp,
  onRoutesChange,
}